package com.citycloud.ccuap.tc.sync.aspect;

import com.citycloud.ccuap.commons.json.JSONData;
import com.citycloud.ccuap.commons.sys.entity.SysProject;
import com.citycloud.ccuap.commons.sys.project.ProjectService;
import com.citycloud.ccuap.tc.sync.dto.DeletedDeptUserDTO;
import com.citycloud.ccuap.tc.sync.constant.GlobalSyncOperation;
import com.citycloud.ccuap.tc.sync.constant.GlobalSyncType;
import com.citycloud.ccuap.tc.sync.dto.SyncDataDto;
import com.citycloud.ccuap.tc.sync.service.IMessageService;
import org.apache.commons.collections.CollectionUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;

@Aspect
@Component
public class DeptDeleteAspect {
    @Autowired
    private ProjectService projectService;

    @Autowired
    private IMessageService messageService;


    @Pointcut("execution(* com.citycloud.ccuap.commons.sys.deptment.DeptmentController.deleteNode())")
    public void deleteDept() {
    }

    @AfterReturning(value = "deleteDept()", returning = "key")
    public void doDeleteDept(JoinPoint joinPoint, Object key) throws Throwable {
        if (key instanceof JSONData) {
            JSONData jsonData = (JSONData) key;
            Map<String, Object> data = (Map) jsonData.getData();
            Long projectId = (Long) data.get("projectId");
            List<Long> deleteList = (List<Long>) data.get("deleteList");
            sendDeletedJmsMessage(deleteList, projectId);
        }
    }

    private void sendDeletedJmsMessage(List<Long> list, Long projectId) {
        // 平台操作删除部门前，各站点已删除导入的对应部门，此处不用考虑
        if (projectId != null && CollectionUtils.isNotEmpty(list)) {
            SysProject project = projectService.findById(projectId);
            if (project != null && project.getMqOff()) {
                DeletedDeptUserDTO deletedDeptUserDTO = new DeletedDeptUserDTO();
                deletedDeptUserDTO.setDeptId(list);
                SyncDataDto<DeletedDeptUserDTO> result = SyncDataDto.of(GlobalSyncType.OBJECT_TYPE_DEPT,
                        GlobalSyncOperation.DELETED, projectId, deletedDeptUserDTO);
                messageService.sendMessageByTopic(result,GlobalSyncType.TOPIC_USER_DEPT);
            }
        }
    }

}
